/**
 * 项目名称：MSH
 * 包名称：com.mt.component.iterceptor
 * 文件名称：LogIterceptor.java
 */
package com.mt.component.iterceptor;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.mt.component.annotation.Logger;
import com.mt.system.domain.OptLog;
import com.mt.system.domain.Permission;


/**
 * 类名称：LogIterceptor <br>
 * 类描述： <br>
 * 创建人： 马腾 <br>
 * 创建时间：Oct 25, 2012 12:45:28 PM <br>
 */
public class LogIterceptor implements MethodInterceptor {
	
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public Object invoke(MethodInvocation method) throws Throwable {
		Object object = null;
		try {
			object = method.proceed();
			if(method.getMethod().isAnnotationPresent(Logger.class)){
				addLog(method.getMethod().getAnnotation(Logger.class).name());
			}
		} catch (Throwable e) {
			throw new Throwable(e);
		}
		return object;
	}
	
	private void addLog(String mark){
		String eql = "from Permission p where p.mark = :mark" ;
		Query query = entityManager.createQuery(eql);
		query.setParameter("mark", mark);
		Permission permission;
		try {
			permission = (Permission) query.getSingleResult();
			OptLog optLog = new OptLog();
			optLog.setOptTime(new Date());
			optLog.setPermission(permission);
			entityManager.persist(optLog);
		} catch (NoResultException e) {
			e.printStackTrace();
		}
	}
}
